/*
 * Copyright 2018 Youchaoshi authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package common.plugins.tbs;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.orhanobut.logger.Logger;
import com.qw.soul.permission.SoulPermission;
import com.qw.soul.permission.bean.Permission;
import com.qw.soul.permission.callbcak.CheckRequestPermissionListener;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import com.tekj.cxqcb.R;
import com.tekj.cxqcb.config.enums.EventBusMsgBean;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import common.tool.StatusBarUtil;
import common.tool.Tools;
import es.dmoral.toasty.Toasty;

import static com.tekj.cxqcb.MainBActivity.User;
import static com.tekj.cxqcb.MainBActivity.getUserID;
import static com.tekj.cxqcb.config.Urls.Domain_H5;
import static common.plugins.tbs.WebCoreChromeClient.REQUEST_CODE_ALBUM;
import static common.plugins.tbs.WebCoreChromeClient.REQUEST_CODE_CAMERA;

/**
 * 基于腾讯X5内核封装的webview公共访问模块
 * Created by JustTong on 2018/12/11.
 */

public class WebCoreActivity extends AppCompatActivity {


    @BindView(R.id.webview_toolbar)
    Toolbar webviewToolbar;
    @BindView(R.id.pb_bar)
    ProgressBar pbBar;
    @BindView(R.id.tbs_content)
    WebView tbsContent;
    @BindView(R.id.content_web_core)
    RelativeLayout contentWebCore;
    @BindView(R.id.img_load)
    ImageView imgLoad;

    private String InputUrl = "http://m.baidu.com";
    private String Title = "";//默认为空时，则自动读取html页面title标签数据，一般为空即可
    private Toolbar toolbar;
    private WebCoreChromeClient webCoreChromeClient;

    private ValueCallback<Uri[]> uploadMessageAboveL;
    private ValueCallback<Uri> uploadMessage;
    private String mCameraFilePath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_web_core);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            StatusBarUtil.StatusBarLightMode(this);
        }
        EventBus.getDefault().register(this);
        ButterKnife.bind(this);
        toolbar = (Toolbar) findViewById(R.id.webview_toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);//开启返回按钮


        try {
            initReceive();
        } catch (Exception e) {
            e.printStackTrace();
        }

        initSet();
    }

    /**
     * 接收Intent参数
     */
    private void initReceive() throws Exception {

        try {
            this.InputUrl = getIntent().getStringExtra("inputurl");
        } catch (Exception ex) {
            Logger.e(ex.toString());
        }
        try {
            this.Title = getIntent().getStringExtra("title");
        } catch (Exception ex) {
            Logger.e(ex.toString());
        }
    }

    private void initSet() {

        pbBar.setMax(100);
        pbBar.setProgressDrawable(this.getResources().getDrawable(R.drawable.color_progressbar));
        RequestOptions options = new RequestOptions()
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE);
        Glide.with(this).load(R.mipmap.ico_load_b).apply(options).into(imgLoad);
        tbsContent.loadUrl(InputUrl);
        WebSettings webSettings = tbsContent.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);//此处为清理再次访问数据
//        优先使用缓存，WebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
//        不使用缓存，WebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);

        webSettings.setBuiltInZoomControls(true);// 隐藏缩放按钮
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);// 排版适应屏幕
        webSettings.setUseWideViewPort(false);// 可任意比例缩放
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setSavePassword(true);
        webSettings.setSaveFormData(true);// 保存表单数据
        webSettings.setGeolocationEnabled(true);// 启用地理定位
        webSettings.setGeolocationDatabasePath("/data/data/com.tekj.cxqcb/databases/");// 设置定位的数据库路径
        webSettings.setDomStorageEnabled(true);
        webSettings.setSupportMultipleWindows(true);// 新加
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);

        tbsContent.addJavascriptInterface(new WebCoreJsInterface(this), "APP");
        tbsContent.setWebViewClient(new WebCoreClient(this, tbsContent));
        webCoreChromeClient = new WebCoreChromeClient(this, pbBar, Title, imgLoad,
                uploadMessageAboveL,
                uploadMessage,
                mCameraFilePath);
        tbsContent.setWebChromeClient(webCoreChromeClient);

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case android.R.id.home://返回按钮操作
                if (tbsContent.canGoBack()) {
                    tbsContent.goBack();// 返回前一个页面

                } else {
                    finish();
                }
                break;

            case R.id.exit://关闭
                finish();
                break;
            case R.id.tv_wz:
                setInputUrl(Domain_H5 + "/store-sale-list");
                break;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && tbsContent.canGoBack()) {
            tbsContent.goBack();// 返回前一个页面
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            return true;
        }


        return super.onKeyDown(keyCode, event);
    }

    MenuItem menuWz;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_webcore_menu, menu);
        menuWz = menu.findItem(R.id.tv_wz).setVisible(InputUrl.contains("store-order"));
        return true;
    }


    @Override
    public void onStart() {
        super.onStart();

    }

    @Override
    public void onStop() {
        super.onStop();

    }

    public void setInputUrl(String inputUrl) {
        InputUrl = inputUrl;
        tbsContent.loadUrl(inputUrl);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void Event(EventBusMsgBean e) {
        switch (e.getmEnumStatus()) {
            case 门店订单:
                menuWz.setVisible(true);
                break;
            case 非门店订单:
                menuWz.setVisible(false);
                break;
            case 车辆详情分享微信:
                final shareWX shareWX = (common.plugins.tbs.shareWX) e.getObject();

                SoulPermission.getInstance().checkAndRequestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        new CheckRequestPermissionListener() {
                            @Override
                            public void onPermissionOk(Permission permission) {
                                showPop(shareWX);
                            }

                            @Override
                            public void onPermissionDenied(Permission permission) {
                                Toasty.normal(WebCoreActivity.this, "缺少存储权限！").show();
                            }
                        });
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Uri imageUri = null;
        //拍照成功和选取照片时
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_ALBUM:

                    if (data != null) {
                        imageUri = data.getData();
                    }

                    break;
                case REQUEST_CODE_CAMERA:

                    if (!TextUtils.isEmpty(webCoreChromeClient.getmCameraFilePath())) {
                        File file = new File(webCoreChromeClient.getmCameraFilePath());
                        Uri localUri = Uri.fromFile(file);
                        Intent localIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri);
                        sendBroadcast(localIntent);
                        imageUri = Uri.fromFile(file);
                        mCameraFilePath = webCoreChromeClient.getmCameraFilePath();
                    }
                    break;
            }
        }

        uploadMessage = webCoreChromeClient.uploadMessage;
        uploadMessageAboveL = webCoreChromeClient.getUploadMessageAboveL();
        //上传文件
        if (uploadMessage != null) {
            uploadMessage.onReceiveValue(imageUri);
            uploadMessage = null;
        }
        if (uploadMessageAboveL != null) {
            uploadMessageAboveL.onReceiveValue(new Uri[]{imageUri});
            uploadMessageAboveL = null;

        }

    }

    private PopupWindow popupWindow;
    private View popupView;
    private TranslateAnimation animation;
    private boolean isLoading = false;

    /**
     * 微信分享弹窗
     */
    private void showPop(final shareWX shareWX) {

        isLoading = false;
        popupView = View.inflate(this, R.layout.pop_share_wx2, null);

        popupWindow = new PopupWindow(popupView, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT, true);
        popupWindow.setOutsideTouchable(true);

        animation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT,
                0, Animation.RELATIVE_TO_PARENT, 0,
                Animation.RELATIVE_TO_PARENT, 1,
                Animation.RELATIVE_TO_PARENT, 0);
        animation.setInterpolator(new AccelerateInterpolator());
        animation.setDuration(200);

        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                Tools.lighton(WebCoreActivity.this);
            }
        });

        LinearLayout llWxHy = popupView.findViewById(R.id.ll_wx_hy);
        LinearLayout llWxPyq = popupView.findViewById(R.id.ll_wx_pyq);

        TextView tvTitle = popupView.findViewById(R.id.tv_title);
        TextView tvSf = popupView.findViewById(R.id.tv_sf);
        TextView tvYg = popupView.findViewById(R.id.tv_yg);
        TextView tvQs = popupView.findViewById(R.id.tv_qs);
        final ImageView imgCarPhoto = popupView.findViewById(R.id.img_car_photo);
//ScrollView
        final ScrollView cv_bg = popupView.findViewById(R.id.cv_bg);
        ImageView ewm = popupView.findViewById(R.id.img_ewm);
        Tools.CreateQRcodeImage("https://cars-cxqc.com/static/carDetail?id=" + shareWX.getId() + "&shareId=" + User.getUserId(),
                ewm,
                WebCoreActivity.this,
                70,
                70);
        final CardView cv_wx = popupView.findViewById(R.id.cv_wx);

        cv_bg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Tools.showAnimation(WebCoreActivity.this,
                        cv_wx,
                        cv_wx.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
            }
        });

        tvTitle.setText(shareWX.getTitle());
        tvSf.setText(shareWX.getDownPay() + "首付");
        tvYg.setText(shareWX.getMonthFeed() + "");
        tvQs.setText(shareWX.getPeriods() + "");

        Picasso.get().load(shareWX.getHeadImage()).into(new Target() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                Tools.lightoff(WebCoreActivity.this);
                imgCarPhoto.setImageBitmap(bitmap);
                isLoading = true;
                popupWindow.showAtLocation(toolbar, Gravity.BOTTOM, 0, 0);
                popupView.startAnimation(animation);
            }

            @Override
            public void onBitmapFailed(Exception e, Drawable errorDrawable) {
                Toasty.normal(WebCoreActivity.this, "生成分享图片失败").show();
            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {

            }
        });


        llWxHy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isLoading) {
                    Toasty.normal(WebCoreActivity.this, "生成分享图片中。。").show();
                    return;
                }
                Tools.download(WebCoreActivity.this,
                        Domain_H5 + "/car-detail/" + shareWX.getId() + getUserID(),
                        User.getUserId(), shareWX.getId(), shareWX.getTitle(),
                        "内容", shareWX.getHeadImage());
                popupWindow.dismiss();
            }
        });
        llWxPyq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isLoading) {
                    Toasty.normal(WebCoreActivity.this, "生成分享图片中。。").show();
                    return;
                }
                Tools.WxSharePhoto(cv_bg, WebCoreActivity.this);
                popupWindow.dismiss();
            }
        });

        RelativeLayout rlBg = popupView.findViewById(R.id.rl_bg);
        rlBg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });


    }
}
